
TARGET=task

BUILD_DIR=output

##### gcc
CROSS_COMPILE ?=arm-none-eabi-

CC=$(CROSS_COMPILE)gcc
AS=$(CROSS_COMPILE)gcc -x assembler-with-cpp
CP=$(CROSS_COMPILE)objcopy
SZ=$(CROSS_COMPILE)size
LD=$(CROSS_COMPILE)ld
DP=$(CROSS_COMPILE)objdump

DRIVER_DIR=../../drivers
SYS_DIR=../../drivers/sys
FREE_RTOS_DIR=../../../RTOS/FreeRTOS
PRINTF_DIR=../../../RTOS/printf

#### src files
SRC_C+=$(wildcard $(DRIVER_DIR)/*.c )
SRC_C+=$(wildcard $(SYS_DIR)/*.c )
SRC_C+=$(wildcard srcs/*.c)
SRC_C+=$(wildcard $(PRINTF_DIR)/*.c )

#freertos dir
SRC_C+=$(wildcard $(FREE_RTOS_DIR)/*.c)
SRC_C+=$(FREE_RTOS_DIR)/portable/MemMang/heap_4.c 
SRC_C+=$(wildcard ../port/*.c)


SRC_S=startup/startup_stm32f103xb.S

SRC_LD=STM32F103XX_FLASH.ld

#### .o files
OBJ_C=$(addprefix $(BUILD_DIR)/,$(notdir $(SRC_C:.c=.o)))
OBJ_S=$(BUILD_DIR)/startup_stm32f103xb.o

#### include dir
INC=-Iinc \
-I$(DRIVER_DIR)/include \
-I$(SYS_DIR) \
-I../port \
-I$(FREE_RTOS_DIR)/include \
-I$(PRINTF_DIR) \
-I../../../RTOS

#### CFLAGS
DEFS=-DUSE_HAL_DRIVER -DSTM32F103xB -DPRINTF_INCLUDE_CONFIG_H
 
CFLAGS= \
-mcpu=cortex-m3 \
-mthumb \
$(DEFS) \
-Wall \
-fdata-sections \
-ffunction-sections \
-Og \
#-Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst))
#-g \
#-gdwarf-2 \
#-MMD -MP -MF"$(@:%.o=%.d)"


#### LINK 
LIBS=-lc -lm -lnosys

LDFLAGS =-mcpu=cortex-m3 \
-Wl,--gc-sections \
-specs=nano.specs -T$(SRC_LD) \
$(LIBS) \
-Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref


### .c path set
vpath %.c $(sort $(dir $(SRC_C) ))

 
#### build
.PHONY:all clean  test dis d c

all: $(BUILD_DIR) $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).bin  $(BUILD_DIR)/$(TARGET).dis
	@echo all

# mkdir 
$(BUILD_DIR):
	mkdir $@

# link elf
$(BUILD_DIR)/$(TARGET).elf:$(OBJ_C) $(OBJ_S)
	@echo  $@
	@$(CC) $(OBJ_C) $(OBJ_S) $(LDFLAGS) -o $@
	@$(SZ) $@

# .c -> .o
$(BUILD_DIR)/%.o : %.c
	@echo CC $<
	@$(CC) -c $(CFLAGS)  $< $(INC) -o $@
	

# .s -> .o
$(OBJ_S):$(SRC_S)
	@echo AS $<
	@$(AS) -c $(CFLAGS) $< $(INC) -o $@

# .elf -> .bin
$(BUILD_DIR)/$(TARGET).bin:$(BUILD_DIR)/$(TARGET).elf
	@echo $@
	@$(CP) -O binary -S $< $@

#.elf -> dis
$(BUILD_DIR)/$(TARGET).dis:$(BUILD_DIR)/$(TARGET).elf
	@echo  $@
	@$(DP) -DS $< > $@
clean:
	rm -rf $(BUILD_DIR)

dis:$(BUILD_DIR)/$(TARGET).elf
	$(DP) -DSh $< > $(BUILD_DIR)/$(TARGET).dis

test:
#	@echo $(SRC_C) 
	@echo $(OBJ_C)  

c:
	make clean

d: 
	make all -j12

#-include $(wildcard $(BUILD_DIR)/*.d)